﻿Public Class CustomListBox
    Inherits ListBox

    Public Sub CustomListBox()
        MyBase.()
    End Sub

    'http://gfaraj.wordpress.com/2008/07/31/custom-sorting-for-listbox-in-c/
    Protected Overloads Overrides Sub Sort() 'protected override
        QuickSort(0, Items.Count - 1)
    End Sub

    Private Sub QuickSort(left As Integer, right As Integer)
        If (right > left) Then

            Dim pivotIndex As Integer = left
            Dim pivotNewIndex As Integer = QuickSortPartition(left, right, pivotIndex)

            QuickSort(left, pivotNewIndex - 1)
            QuickSort(pivotNewIndex + 1, right)
        End If
    End Sub

    Private Function QuickSortPartition(eft As Integer, right As Integer, pivot As Integer) As Integer
    Dim pivotValue As VariantType = (IComparable) Items(pivot)
        Swap(pivot, right)

        Dim istoreIndex As Integer = Left()
        For i As Integer = Left() To right - 1

            If (pivotValue.CompareTo(Items(i)) >= 0) Then
                Swap(i, storeIndex)
                storeIndex += 1
            End If
        Next

        Swap(storeIndex, right)
        Return storeIndex
    end Funtion

    Private Sub Swap(left As Integer, right As Integer)
        Dim temp As VariantType = Items(left)
        Items(left) = Items(right)
        Items(right) = temp
    End Sub

End Class
